import { defineStore } from 'pinia'
import http from "@/utils/request.js";
// 从 localStorage 获取初始状态
const getInitialState = () => {
  const savedUser = localStorage.getItem('user')
  if (savedUser) {
    const { name, isLoggedIn } = JSON.parse(savedUser)
    return {
      name,
      isLoggedIn
    }
  }
  return {
    name: '',
    isLoggedIn: false
  }
}

export const useUserStore = defineStore('user', {
  state: () => getInitialState(),

  getters: {
    getUserName: (state) => state.name,
    getLoginStatus: (state) => state.isLoggedIn
  },

  actions: {
    setUser(name) {
      this.name = name
    },
    async login(data) {
     let res =  await http.post('/login',data)
      console.log(res)
      // 存储用户信息到 localStorage
      localStorage.setItem('user', JSON.stringify({
        name: data.phone,
        isLoggedIn: true
      }))
      localStorage.setItem('user', JSON.stringify(res.userInfo))
      localStorage.setItem('token', JSON.stringify(res.token))
      this.isLoggedIn = true
    },
    logout() {
      this.name = ''
      this.isLoggedIn = false
    }
  }
})
